package com.gongpingjialoan.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.car.AgentReCommendCarActivity;
import com.gongpingjialoan.activity.car.CarBuyDetailActivity;
import com.gongpingjialoan.bean.AgentRecommand;
import com.gongpingjialoan.bean.SpecificBean;
import com.gongpingjialoan.utility.AbStrUtil;
import com.gongpingjialoan.utility.AgentGroupData;
import com.gongpingjialoan.utility.GetAgentGroupData;
import com.gongpingjialoan.utility.Utils;
import com.gongpingjialoan.widget.MyGridView;
import com.google.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by chuang on 2016/10/27.
 */
public class AgentReCommendAdapter extends BaseExpandableListAdapter {


    private AgentRecommand mAgentRecommand;

    private Context mContext;

    private LayoutInflater mLayoutInflater;

    private Handler mHandler;

    private List<String> types;

    private List<String> newTypes;

    private Map<String, SpecificBean> mSpecificBeanMap;
    private Map<String, List<AgentRecommand.DataBean.RecordsBean>> datas;


    public AgentReCommendAdapter(AgentRecommand agentRecommand, Context context, Handler handler) {
        mAgentRecommand = agentRecommand;
        mContext = context;
        mHandler = handler;
        mLayoutInflater = LayoutInflater.from(context);
        types = new ArrayList<>();
        datas = new HashMap<>();
        mSpecificBeanMap = new HashMap<>();
        newTypes = new ArrayList<>();
    }

    public void clear() {
        types.clear();
        datas.clear();
        mSpecificBeanMap.clear();
        newTypes.clear();
        notifyDataSetChanged();
    }


    private void init() {
        if (mAgentRecommand != null && mAgentRecommand.getData() != null) {
            List<AgentRecommand.DataBean.RecordsBean> records = mAgentRecommand.getData().getRecords();
            try {
                LinkedTreeMap<String, SpecificBean> treeMap = mAgentRecommand.getData().getRecommend_filters();

                Iterator<String> keys = treeMap.keySet().iterator();
                while (keys.hasNext()) {
                    String filter_type = keys.next();
                    mSpecificBeanMap.put(filter_type, treeMap.get(filter_type));
                    if (!newTypes.contains(filter_type))
                        newTypes.add(filter_type);
                }
                int size = newTypes.size();
                for (AgentRecommand.DataBean.RecordsBean r : records) {
                    for (int i = 0; i < size; i++) {
                        if (!types.contains(r.getFilter_id())) {
                            types.add(r.getFilter_id());
                            datas.put(r.getFilter_id(), new ArrayList<AgentRecommand.DataBean.RecordsBean>());
                        }
                        if (newTypes.get(i).equals(r.getFilter_id())) {
                            datas.get(r.getFilter_id()).add(r);
                        }
                    }
                }
            } catch (Exception e) {
                Utils.LogD("Recommend_filters" + "解析报错");
            }
        }
    }

    public void setData(AgentRecommand agentRecommand) {
        this.mAgentRecommand = agentRecommand;
        init();
        notifyDataSetChanged();
    }

    @Override
    public int getGroupCount() {
        return datas.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        try {
            return datas.get(types.get(groupPosition)).size();
        } catch (Exception e) {
        }
        return 0;
    }


    @Override
    public Object getGroup(int groupPosition) {
        return types.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return datas.get(types.get(groupPosition)).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }


    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        ParentViewHolder holder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.agent_recommand_parent_item, null);
            holder = new ParentViewHolder();
            holder.mMyGridView = (MyGridView) convertView.findViewById(R.id.grid);
            convertView.setTag(holder);
        } else {
            holder = (ParentViewHolder) convertView.getTag();
        }
        List<AgentGroupData> agentGroupDatas = GetAgentGroupData.getAgentData(mAgentRecommand, mSpecificBeanMap, (String) getGroup(groupPosition));
        holder.mMyGridView.setAdapter(new AgentGridAdapter(mContext, agentGroupDatas));
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.agent_recommand_item, null);
            holder = new ViewHolder();
            holder.imgThumbnail = (ImageView) convertView.findViewById(R.id.pic);
            holder.tvCarTitle = (TextView) convertView.findViewById(R.id.carName);
            holder.carModel = (TextView) convertView.findViewById(R.id.model);
            holder.priceTextView = (TextView) convertView.findViewById(R.id.price);
            holder.evalPrice = (TextView) convertView.findViewById(R.id.eval_price);
            holder.unlikeTv = (TextView) convertView.findViewById(R.id.unlike_tv);
            holder.phoneIm = (TextView) convertView.findViewById(R.id.agent_contact);
            holder.timeTextView = (TextView) convertView.findViewById(R.id.time);
            holder.mileTextView = (TextView) convertView.findViewById(R.id.mile);

            holder.agentTv = (TextView) convertView.findViewById(R.id.agent_count_tv);
            holder.statusTextView = (TextView) convertView.findViewById(R.id.status);
            convertView.setTag(R.id.tag_first, holder);
        } else {
            holder = (ViewHolder) convertView.getTag(R.id.tag_first);
        }
        final AgentRecommand.DataBean.RecordsBean record = (AgentRecommand.DataBean.RecordsBean) getChild(groupPosition, childPosition);

        if (record != null) {
            holder.unlikeTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Message msg = Message.obtain();
                    msg.what = AgentReCommendCarActivity.UNLIKE;
                    msg.obj = record.getId();
                    mHandler.sendMessage(msg);
                }
            });
            holder.phoneIm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + record.getPhone()));
                    mContext.startActivity(intent);
                }
            });
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, CarBuyDetailActivity.class);
                    intent.putExtra("typevalue", String.valueOf(record.getCar().getId()));
                    mContext.startActivity(intent);
                }
            });
            holder.agentTv.setText("经纪人已服务" + record.getDealer_serve_count() + "人");

            if ("".equals(record.getCar().getModel_detail_slug_zh())) {
                holder.tvCarTitle.setText(record.getCar().getTitle());
            } else {
                holder.tvCarTitle.setText(record.getCar().getModel_detail_slug_zh());
            }

            if ("sale".equals(record.getCar().getStatus())) {
                holder.statusTextView.setVisibility(View.GONE);
            } else {
                holder.statusTextView.setVisibility(View.VISIBLE);
            }
            holder.carModel.setText(record.getCar().getModel_slug_zh());
            holder.mileTextView.setText(record.getCar().getYear() + "年上牌/" + record.getCar().getMile() + "万公里/" + record.getCar().getCity());
            holder.priceTextView.setText(record.getCar().getPrice());
            String expertPrice = mSpecificBeanMap.get(record.getFilter_id()).getPrice();
            double comparePrice = AbStrUtil.get2Double(Double.parseDouble(record.getCar().getPrice()) - Double.parseDouble(expertPrice));
            String priceCompare = comparePrice + "万元";
            if(comparePrice > 0) {
                String str_price = "(商家已降价" + priceCompare + ")";
                holder.evalPrice.setText(Utils.changeColor(mContext, str_price, 6, 6 + priceCompare.length(), R.color.text_orange_dark));
            }else if(comparePrice == 0){
                holder.evalPrice.setText("(和您购车预算持平)");
            }else{
                holder.evalPrice.setText("");
            }
            Glide.with(mContext).load(record.getCar().getThumbnail()).placeholder(R.drawable.car_loading).centerCrop().crossFade().into(holder.imgThumbnail);
        }
        return convertView;

    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    public static class ViewHolder {

        public TextView phoneIm;

        public ImageView imgThumbnail;

        public TextView tvCarTitle;

        public TextView carModel;

        public TextView timeTextView;

        public TextView mileTextView;

        public TextView priceTextView;

        public TextView unlikeTv;

        public TextView agentTv;

        public TextView evalPrice;

        public TextView statusTextView;

    }

    public static class ParentViewHolder {
        public MyGridView mMyGridView;
    }
}

